package com.biejiaogroup.librarymanager.controller;

import com.biejiaogroup.librarymanager.entity.User;
import com.biejiaogroup.librarymanager.entity.vo.MessageModel;
import com.biejiaogroup.librarymanager.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @Author: JesseChan
 * @Date: 2022/5/11
 */

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        //1.接收客户端请求（用户名、密码）
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");

        //2.调用service方法 返回消息模型
        MessageModel messageModel = userService.userLogin(userName, userPassword);

        //3.
        if (messageModel.getCode() == 1)
        {
            //登陆成功
            request.getSession().setAttribute("user", messageModel.getObject());
            request.getSession().setAttribute("login", true);
            User user = (User) messageModel.getObject();
            String headshotURL = "src/headshots/" + user.getUserID() + ".jpg";
            File file = new File(getServletContext().getRealPath(headshotURL));
            if (file.exists())
            {
                request.getSession().setAttribute("headshotURL", headshotURL);
            }
            else
            {
                request.getSession().setAttribute("headshotURL", "src/headshots/default.jpg");
            }

            response.sendRedirect("index.jsp");
        }
        else
        {
            //登陆失败
            request.setAttribute("messageModel", messageModel);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
